rm(list= ls())

library(lfe)
library(tidyverse)

## Load Election Data

dat <- readRDS('data/fed_elections_kreise.rds') %>%
  filter(year >= 1953) %>% 
  filter(year <= 1965) %>%
  filter(type == 'Stadtkreis') 

## Define outcomes 

outcomevars <- c('fdp',
                 'far_right_vs_excl_dp',
                 'cdu_csu',
                 'spd')

## Define potential pre/post years 

post_years <- c(1957, 1961, 1965)

## Estimate across periods/outcomes 

res_all <- lapply(post_years, function(post_year){
  
  pre_year <- post_year - 4
  
  lapply(outcomevars, function(dv){
    
    ## Define treated * post variable 
    
    dat_new <- dat %>% 
      filter(year %in% c(post_year, pre_year)) %>% ## estimate 2 period models 
      mutate(post = ifelse(year >= post_year, 1, 0)) %>%
      mutate(treated_post = n_syn_bin * post) %>%
      mutate(treated = n_syn_bin) %>%
      mutate(year = as.character(year))

    m1 <- as.formula(paste(dv, 'treated_post | county_id_1950 + year | 0 | county_id_1950', sep = '~'))
  
    ## Estimate 
    
    tryCatch({
      
      results <- felm(m1, data = dat_new) %>%
        broom::tidy(conf.int = T) %>%
        filter(term == 'treated_post') %>%
        mutate(model_formula = deparse(m1)[1]) %>%
        mutate(outcome = dv,
               post_year = post_year,
               time_period = paste(pre_year, post_year, sep = ' - ')) }, 
      
      error = function(e){cat("ERROR :",conditionMessage(e), "\n")})
    
  }) %>% reduce(rbind)
}) %>% reduce(rbind) %>%
  arrange(outcome, post_year)

## Add labels for outcome / treatment 

res_all <- res_all %>%
  mutate(outcome_label = recode(outcome,
                                `far_right_vs_excl_dp` = 'Far right\n(NPD/DRP)',
                                `spd` = 'SPD',
                                `cdu_csu` = 'CDU/CSU',
                                `fdp` = 'FDP')) %>%
  mutate(outcome_label = fct_relevel(outcome_label, c('FDP', 'Far right\n(NPD/DRP)', 'SPD')))


pd <- position_dodge(.3)

ggplot(res_all, 
       aes(x = outcome_label, y = estimate, ymin = conf.low, ymax = conf.high, 
           col = time_period,
           shape = time_period)) + 
  geom_errorbar(width = 0, position = pd) + 
  geom_point(position = pd) + 
  geom_hline(yintercept = 0, linetype = 'dotted') + 
  theme_classic() + 
  labs(x = '',
       y = 'Effect estimate',
       col = 'Time-period',
       shape = 'Time-period') + 
  theme() + 
  scale_colour_manual(values = c('gray', 'gray', 'black'))  





